package com.letv.core.sysletvplayer.base.impl;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.letv.android.sdk.R;
import com.letv.core.sysletvplayer.base.BasePlayerController;
import com.letv.core.sysletvplayer.constants.SysConstants;
import com.letv.core.sysletvplayer.utils.Tools;

import java.io.File;

public class LocalPlayerController extends BasePlayerController implements OnPreparedListener, OnErrorListener, OnCompletionListener {

	/** 刷新进度条的handler标识 */
	private final static int HANDLER_TIME = 101;
	/** 0.5秒刷新一次进度条 */
	private final static int HANDLER_TIME_DELAYED = 500;
	/** 视频路径 */
	private String mUrl;
	/**视频标题**/
	private String mTitle;
	/** seek时间点 */
	private int mSeekTime;
	/** 总时间 */
	private long mTotleTime;
	/** 当前时间 */
	private long mCurTime;
	/** 最后（上一次）播放的时间 */
	private long mLastTime;
	
	/**
	 * 刷新进度handler
	 * */
	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_TIME:
				mCurTime = activity.getPlayFragment().getCurrentPosition();
				if (mLastTime == mCurTime) {
					mBasePlayerPannel.showLoading();
				} else {
					mBasePlayerPannel.finishLoading();
				}
				mBasePlayerPannel.updateProgress((int) mCurTime / 1000,
						(int) mTotleTime / 1000);
				handler.sendEmptyMessageDelayed(HANDLER_TIME,
						HANDLER_TIME_DELAYED);
				
//				Log.i("chenyg", "handler--->刷新进度条");
				break;
			}
			return false;
		}
	});

	public LocalPlayerController(LocalPlayerActivity activity) {
		super(activity);
	}
	
	@Override
	protected void readArguments() {
		Intent intent = activity.getIntent();
		mUrl = intent.getStringExtra("url");
		mSeekTime = intent.getIntExtra("seek", 0);
		mTitle = intent.getStringExtra("title");
		if (TextUtils.isEmpty(mUrl)) {
			if ((null != intent) && null != intent.getData()) {
				Uri uriPath = intent.getData();
				String scheme = uriPath.getScheme();
				if (scheme == null || scheme.equals("file")) {
					mUrl = uriPath.getPath();
				} else {
					mUrl = uriPath.toString();
				}
			}
		}
		Log.i("chenyg", "readArguments()-------->mUrl=" + mUrl);
//		mUrl = "/sdcard/OpenCV.mp4"; // 本地地址，测试
//		mUrl = "http://121.18.237.200:80/play/FB8F73735167BAB1373B6812A346162D6D5B7C06.mp4";

	}
	
	@Override
	protected void initLayout() {
		
		mBasePlayerPannel = new LocalPlayerPannel(activity);
//		this.setPannelHandler(mBasePlayerPannel);
		mBasePlayerPannel.setPlayerController(this);
//		activity.SetSystemInfoListener((LocalPlayerPannel)mBasePlayerPannel);
		activity.SetSystemInfoListener(this);
		activity.getPlayUpper().addView(mBasePlayerPannel.getContentView());
		
		mBasePlayerPannel.initVolume(getCurSoundVolume(), getMaxSoundVolume());
		mBasePlayerPannel.showLoading();//add by wangkun  (去掉之前的progressbar 换做animation旋转动画)
		
		if (checkUrlValid(mUrl)) {
			int[] resolation = checkResolution(mUrl);
			boolean islandscape = true;
			if (resolation != null) {
				if (resolation[0] > resolation[1]) {
					Tools.screenLandscape(activity);
					islandscape = true;
				} else if (resolation[0] <= resolation[1]) {
					Tools.screenPortrait(activity);
					islandscape = false;
				}
			}
			mBasePlayerPannel.initTitle(TextUtils.isEmpty(mTitle)?getMediaName(mUrl):mTitle, islandscape);
			activity.getPlayFragment().setPlayingOrStart(true);
			activity.getPlayFragment().playLocal(mUrl, mSeekTime);
			mBasePlayerPannel.play();
		}
		activity.getPlayFragment().setOnPreparedListener(this);
		activity.getPlayFragment().setOnCompletionListener(this);
		activity.getPlayFragment().setOnErrorListener(this);
	}
	
	/**
	 * 检查播放地址有效性
	 * @return
	 */
	public boolean checkUrlValid(String url) {
		if(TextUtils.isEmpty(url)) {
			Toast.makeText(activity, "播放地址为空！", Toast.LENGTH_SHORT).show();
			return false;
		}else if(!new File(url).exists()){
			Toast.makeText(activity, "文件不存在！", Toast.LENGTH_SHORT).show();
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 获取视频宽高分辨率
	 * 
	 * @param path
	 * @return
	 */
	private int[] checkResolution(String path) {
		MediaPlayer mediaPlayer = null;
		try {
			mediaPlayer = MediaPlayer.create(activity, Uri.parse(path));
			if (mediaPlayer != null) {
				int width = mediaPlayer.getVideoWidth();
				int height = mediaPlayer.getVideoHeight();
				return new int[] { width, height };
			}
			return null;
		} finally {
			if (mediaPlayer != null) {
				mediaPlayer.release();
				mediaPlayer = null;
			}
		}
	}

	
	
	/**
	 * 获取多媒体文件名称
	 */
	private String getMediaName(String url) {
		if (checkUrlValid(url)) {
			int start = url.lastIndexOf("/");
			// int end=url.lastIndexOf(".");
			int end = url.length();
			if (start != -1 && end != -1) {
				return activity.getResources().getString(R.string.local_title_tag)+url.substring(start + 1, end);
			}
		}
		return null;
	}

	@Override
	public void onSeekTo(int progress) {
		activity.getPlayFragment().seekTo(progress * 1000);
	}

	@Override
	public void onStart() {
		startHandler();
		activity.getPlayFragment().start();
	}

	@Override
	public void onPause() {
		stopHandler();
		activity.getPlayFragment().pause();
	}
	
	@Override
	public boolean isPlaying() {
		return activity.getPlayFragment().isPlaying();
	}

	@Override
	public void onBack() {
		activity.finish();
	}

	@Override
	public void onForward() {
		activity.getPlayFragment().forward();
	}

	@Override
	public void onRewind() {
		activity.getPlayFragment().rewind();
	}
	
	@Override
	public void onZoom(int type) {
		
	}

	@Override
	public void onFull() {

	}

	@Override
	public void onHalf() {

	}

	@Override
	public void onShare(String content) {

	}
	
	@Override
	public void onSoundChange(int cur, int max) {
		setSoundVolume(cur, false);
	}
	
	public void changeVolumeByTouch(int cur, int max) {
		mBasePlayerPannel.updateVolume(cur, max);
	}
	
	public void changeProgressByTouch(int curPos, int total, boolean isfinish) {
		if (activity.getPlayFragment().isPlaying()) {
			if (!isfinish) {
				stopHandler();
			} else {
				startHandler();
			}
		}
		mBasePlayerPannel.updateProgress(curPos / 1000, total / 1000);
	}
	
	@Override
	public void onDlna() {
		if(checkRemoteControl()) {
			// 启动设备列表的Activity
//	        Intent intent = new Intent();
//	        intent.setAction(Constant.ACTION_PICK_REMOTE_DEVICE);
//	        activity.startActivityForResult(intent, LocalPlayerActivity.REQUEST_CODE);
		} else {
			Toast.makeText(activity, R.string.local_no_dlna_message, Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * 检查手机是否安全手机遥控器应用
	 * @return
	 */
	private boolean checkRemoteControl() {
		PackageInfo packageInfo;
		try {
			packageInfo = activity.getPackageManager().getPackageInfo(
					"com.letv.android.remotecontrol", 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		return (packageInfo != null) ? true : false;
	}
	
	@Override
	public void onSmall() {
		if (activity != null) {
			activity.finish();
		}
		Bundle mBundle = new Bundle();
		mBundle.putBoolean("isLive", false);
		/*mBundle.putString("albumtitle","本地小窗");
		mBundle.putString("order", "0");
		mBundle.putLong("aid", 0);
		mBundle.putLong("vid", 0);*/
		mBundle.putBoolean("isDolby", false);
		/**判断是否来自于本地播放器，小窗返回全屏时使用**/
		mBundle.putBoolean("isFromLocal", true);
		mBundle.putInt("launch_mode", 0);
		
		/*mBundle.putSerializable("album", album);
		mBundle.putInt("curPage", curPage);*/
		mBundle.putString("url",mUrl);
		//mBundle.putLong("lastvid", getLastVideoPos(videos));
		int seek = activity.getPlayFragment().getCurrentPosition();
		Log.i("wxf", "local seek:"+seek);
		mBundle.putLong("seek",seek/1000);
		
		
		mBundle.putString("pcode",SysConstants.PCODE);
		mBundle.putString("version",SysConstants.VERSION);
		/**在小窗中通过此字段来判断加载的videoView类型**/
		mBundle.putString("video_format","no");

		
		Intent intent = new Intent();
		intent.setAction("com.letv.android.pipService");
		intent.putExtra("play_parameter",mBundle);
        activity.startService(intent);
	}
	
	@Override
	public void onStartTrackingTouch() {
		stopHandler();
	}

	@Override
	public void onStopTrackingTouch() {
		startHandler();
	}
	
	public void onDestroy() {
		super.onDestroy();
		if (handler != null) {
			handler.removeCallbacksAndMessages(null);
			handler = null;
		}

		activity.getPlayFragment().stopPlayback();
	}
	
	private void startHandler() {
		/** 开始刷新进度 */
		handler.removeMessages(HANDLER_TIME);
		handler.sendEmptyMessage(HANDLER_TIME);
	}
	
	private void stopHandler() {
		handler.removeMessages(HANDLER_TIME);
		handler.removeCallbacksAndMessages(null);
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
//		Log.i("chenyg", "播放准备完成");
		mTotleTime = activity.getPlayFragment().getDuration();
		mCurTime = activity.getPlayFragment().getCurrentPosition();
		/** 初始化播放页进度控制条 */
		mBasePlayerPannel.initProgress((int) mCurTime / 1000,
				(int) mTotleTime / 1000);
		startHandler();
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) {
		activity.finish(); //播放完成退出当前界面
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.finishLoading();
		}
		Toast.makeText(activity, R.string.local_player_error, Toast.LENGTH_SHORT).show();
		activity.finish(); //播放出错退出当前界面
		return false;
	}

	@Override
	public void onTimeChange() {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onTimeChange();
		}
	}

	@Override
	public void onBatteryChange(int status, int curPower) {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onBatteryChange(status, curPower);
		}
	}

	@Override
	public void onNetChange() {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onNetChange();
		}
	}

	@Override
	public void onScreenOn() {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onScreenOn();
		}
	}

	@Override
	public void onScreenOff() {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onScreenOff();
		}
	}

	@Override
	public void onUserPersent() {
		if(mBasePlayerPannel != null) {
			mBasePlayerPannel.onUserPersent();
		}
	}
	
	/**
	 * DLNA推送到手机端
	 * @param info
	 */
//	public void pushPlay(DeviceInfo info) {
//		mDeviceInfo = info;
//
//		Intent intent02 = new Intent();
//		intent02.setClassName("com.letv.android.remotedevice",
//                "com.letv.android.remotedevice.service.RemoteDeviceManagerService");
//        activity.bindService(intent02, connection, Context.BIND_AUTO_CREATE);
//
//	}
	
//	private RemoteDeviceManager mRemoteDeviceManager = null;
//	private DeviceInfo mDeviceInfo = null;
    
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            mRemoteDeviceManager = RemoteDeviceManager.Stub.asInterface(service);
//
//            if(mDeviceInfo != null) {
//    			try {
//    				mRemoteDeviceManager.playMedia(mDeviceInfo.deviceId, Uri.parse(mUrl), 0);
//    			} catch (RemoteException e) {
//    				e.printStackTrace();
//    			}
//    		}
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        	
        }
    };

}
